package com.scs.application.modules.report.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.modules.base.util.CommonService;
import com.scs.application.modules.report.entity.GridField;
import com.scs.application.modules.report.service.ConfigService;
import com.scs.application.modules.report.service.GridFieldService;
import com.scs.application.modules.sys.model.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 网格字段配置 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/report/grid_field")
public class GridFieldController extends CrudController<GridFieldService, GridField>{
    @Autowired
    ConfigService configService;
    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    @Override
    public RestResult saveItem(@Valid @RequestBody GridField entity) {
        boolean isOk = service.saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        CommonService.cachereport(entity.getReportId());
        return RestResult.ok("数据保存成功", entity);
    }

    /**
     * 删除数据
     */
    @DeleteMapping("/delete")
    public RestResult deleteItems(@RequestBody Map<String, Object> para) {
        List<Serializable> ids = (List<Serializable>) para.get("ids");
        Boolean isOk = service.removeCascadeByIds(ids);
        if (!isOk) {
            return RestResult.error("数据删除失败<br>可能所操作数据已被删除，请刷新页面重新尝试操作");
        }
        List<GridField> gridFieldList = service.list(Wrappers.<GridField>query().in("id",ids));
        if (gridFieldList != null && gridFieldList.size() > 0){
            CommonService.cachereport(gridFieldList.stream().map(GridField::getReportId).distinct().collect(Collectors.toList()).get(0));
        }

        return RestResult.ok("数据删除成功");
    }
}
